﻿namespace Practices.SharePoint.Apps {
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Taxonomy;
    using Microsoft.SharePoint.WebControls;
    using Microsoft.SharePoint.WebPartPages;
    using System;
    using System.Collections.Generic;
    using System.Web.UI;


    public partial class PackagePage : LayoutsPageBase {
        protected bool RunWithElevatedPrivileges {
            get {
                return true;
            }
        }

        private AppCatalogAccessor catalogAccessor;
        protected AppCatalogAccessor CatalogAccessor {
            get {
                if (catalogAccessor == null) {
                    catalogAccessor = new AppCatalogAccessor(RunWithElevatedPrivileges);
                }
                return catalogAccessor;
            }
        }

        protected SPListItem Item {
            get {
                string queryString = Request.QueryString["ProductId"];
                if (!string.IsNullOrEmpty(queryString)) {
                    Guid productId = Guid.Empty;
                    if (Guid.TryParse(queryString, out productId)) {
                        SPListItem item = CatalogAccessor.GetByProductId(productId);
                        return item;
                    }
                }
                return null;
            }
        }

        protected void Page_Load(object sender, EventArgs e) {
            if (!Page.IsPostBack) {
                var categories = GetTaxonomyFields();
                CategoryRepeater.DataSource = categories;
                CategoryRepeater.DataBind();
            }
            
            //LiteralControl fieldNameControl = new LiteralControl() {
            //    Text = taxonomyField.Title
            //};
            XsltListViewWebPart listView = null;

            TaxonomyWebTaggingControl fieldValueControl = new TaxonomyWebTaggingControl() {
                //ID = field.InternalName,
                //SSPList = taxonomyField.SspId.ToString(),
                //TermSetList = taxonomyField.TermSetId.ToString(),
                //AnchorId = taxonomyField.AnchorId,
                //IsMulti = taxonomyField.AllowMultipleValues,
                //Text = string.Format("{0}|{1}", "", ""),
            };
            //InitTaxonomyFieldControls(TaxonomyWebTaggingControls);
        }

        protected IEnumerable<TaxonomyField> GetTaxonomyFields() {
            foreach (SPField field in CatalogAccessor.List.Fields) {
                if (field.FieldValueType == typeof(TaxonomyFieldValue) ||
                    field.FieldValueType == typeof(TaxonomyFieldValueCollection)) {
                        yield return field as TaxonomyField;
                }
            }
        }
    }
}
